using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Sherwood.Content.DO.Model;
using Sherwood.Content.Tests;
using Sherwood.Samples.ArticleMeta;
using Xtensive.Core;
using Xtensive.Storage;
using Xtensive.Storage.Configuration;

namespace Sherwood.Content.DO.Tests
{
    [TestClass]
    public abstract class AutoBuildTest
    {
        private Session _session;
        private TransactionScope _transactionScope;
        public static Domain Domain { get; protected set; }

        [AssemblyInitialize]
        public static void TestFixtureSetUp(TestContext testContext)
        {
            var config = BuildConfiguration();
            Domain = BuildDomain(config);
            FillWithTestData();
        }

        [AssemblyCleanup]
        public static void TestFixtureTearDown()
        {
            Domain.DisposeSafely();
        }

        [TestInitialize]
        public virtual void TestSetup()
        {
            _session = Session.Open(Domain);
            _transactionScope = Transaction.Open();
        }

        [TestCleanup]
        public virtual void TestTearDown()
        {
            _transactionScope.Dispose();
            _session.Dispose();
        }
        
        static DomainConfiguration BuildConfiguration()
        {
            return DomainConfiguration.Load("Default");
        }

        public static Domain BuildDomain(DomainConfiguration configuration)
        {
            try
            {
                return Domain.Build(configuration);
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
        }

        private static void FillWithTestData()
        {
            using (Session.Open(Domain))
            {
                using (var t = Transaction.Open())
                {
                    var client = new Client("SampleClient", "My test client")
                                     {
                                         PublicKey = SampleClient.PublicKey
                                     };
                    var record = new Model.Record(client, "1", "Test Record");
                    var meta = new ArticleMeta(record, client);
                    meta.Author = "Joe Smith";
                    meta.PublishDate = new DateTime(2010, 4, 1);

                    t.Complete();
                }
            }
        }
    }
}
